<?php

namespace addons\Patrol\merchant\controllers;

use addons\Patrol\common\models\PatrolClasses;
use addons\Patrol\common\models\PatrolRecord;
use addons\Patrol\common\models\PatrolPlace;
use common\helpers\ExcelHelper;
use Yii;
use common\traits\Curd;
use common\models\base\SearchModel;
use addons\Patrol\merchant\controllers\BaseController;
use common\enums\StatusEnum;
use yii\db\Expression;
use yii\helpers\Json;


class RecordController extends BaseController
{
    use Curd;


    public $modelClass = PatrolRecord::class;


    /**
     * 首页
     *
     * @return string
     * @throws \yii\web\NotFoundHttpException
     */
    public function actionIndex()
    {
        $searchModel = new SearchModel([
            'model' => $this->modelClass,
            'scenario' => 'default',
            'relations' => ['member' => ['realname'], 'place' => ['name'], 'patrolClasses' => ['title']], // 关联 member 表的 nickname 字段
            'partialMatchAttributes' => ['member.realname', 'place.name', 'patrolClasses.title'], // 模糊查询，注意 member_nickname 为关联表的别名 表名_字段
            'defaultOrder' => [
                'id' => SORT_DESC
            ],
            'pageSize' => $this->pageSize
        ]);
        $search = $params = Yii::$app->request->queryParams;
        $created_time = [];
        if (!empty($search['SearchModel']['created_at'])) {
            list($start, $end) = explode('/', $params['SearchModel']['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between', PatrolRecord::tableName().'.created_at', $start, $end];
            unset($params['SearchModel']['created_at']);
        }
        $dataProvider = $searchModel->search($params);
//        if (Yii::$app->id == 'merchant' && Yii::$app->user->identity->role_id != 0)
//            $dataProvider->query
//                ->andWhere(['member_id' => Yii::$app->user->id]);
//        if (Yii::$app->id == 'merchant' && Yii::$app->user->identity->role_id == 0)
//            $dataProvider->query
//                ->andWhere([PatrolRecord::tableName().'.merchant_id' => $this->getMerchantId()]);

        !empty($created_time) ? $dataProvider->query
            ->andWhere($created_time) : $dataProvider->query
            ->andFilterWhere([PatrolRecord::tableName().'.merchant_id' => $this->getMerchantId()]);
        if(Yii::$app->id == 'merchant'&&Yii::$app->user->identity->department_id!=0)
            $dataProvider->query
                ->andWhere([PatrolRecord::tableName().'.member_id' => Yii::$app->user->id]);
        if(empty($search['SearchModel'])) $search['SearchModel']=['place.name'=>'','patrolClasses.title'=>'','member.realname'=>'','created_at'=>'','state'=>''];
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'searchModel' => $searchModel,
            'search' => $search,
            'places' => PatrolPlace::getDropDown(),
        ]);
    }


    public function actionCreate()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);

        $model->member_id = Yii::$app->user->id;
        // ajax 校验
        $this->activeFormValidate($model);

        if ($model->load(Yii::$app->request->post())) {
            $record = \addons\Patrol\common\models\PatrolRecord::find()->andWhere(['member_id' => Yii::$app->user->id, 'place_id' => $model->place_id, 'classes_id' => $model->classes_id])->one();
            if ($record && date("Y-m-d", $record->created_at) == date("Y-m-d", time()))
                return $this->message("该班次已经巡更过了，不需要重复巡更打卡！", $this->redirect(Yii::$app->request->referrer), 'error');
            $where = new Expression("FIND_IN_SET(:supplier, check_date)", [":supplier" => date("Y-m-d", time())]);
            $plans = \addons\Patrol\common\models\PatrolPlan::find()->andWhere($where)->andWhere(['member_id' => Yii::$app->user->id, 'place_id' => $model->place_id, 'classes_id' => $model->classes_id])->one();
            if (!$plans)
                return $this->message("没有该班次！", $this->redirect(Yii::$app->request->referrer), 'error');
            $model->begin_time = $plans->begin_time;
            $model->end_time = $plans->end_time;
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('create', [
            'model' => $model,
            'places' => PatrolPlace::getDropDown(),
            'classes' => PatrolClasses::getDropDown(),

        ]);
    }
    public function actionEdit()
    {
        $id = Yii::$app->request->get('id', null);
        $model = $this->findModel($id);
        $model->covers = Json::decode($model->covers);

        $model->member_id = Yii::$app->user->id;
        // ajax 校验
        $this->activeFormValidate($model);

        if ($model->load(Yii::$app->request->post())) {
            $record = \addons\Patrol\common\models\PatrolRecord::find()->andWhere(['member_id' => Yii::$app->user->id, 'place_id' => $model->place_id, 'classes_id' => $model->classes_id])->one();
            if ($record && date("Y-m-d", $record->created_at) == date("Y-m-d", time()))
                return $this->message("该班次已经巡更过了，不需要重复巡更打卡！", $this->redirect(Yii::$app->request->referrer), 'error');
            $where = new Expression("FIND_IN_SET(:supplier, check_date)", [":supplier" => date("Y-m-d", time())]);
            $plans = \addons\Patrol\common\models\PatrolPlan::find()->andWhere($where)->andWhere(['member_id' => Yii::$app->user->id, 'place_id' => $model->place_id, 'classes_id' => $model->classes_id])->one();
            if (!$plans)
                return $this->message("没有该班次！", $this->redirect(Yii::$app->request->referrer), 'error');
            $model->begin_time = $plans->begin_time;
            $model->end_time = $plans->end_time;
            !empty($model->covers) && $model->covers = Json::encode($model->covers);

            return $model->save()
                ? $this->redirect(['index'])
                : $this->message($this->getError($model), $this->redirect(['index']), 'error');
        }
        return $this->renderAjax('edit', [
            'model' => $model,
            'places' => PatrolPlace::getDropDown(),
            'classes' => PatrolClasses::getDropDown(),

        ]);
    }
    /**
     * 删除
     *
     * @param $id
     * @return mixed
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public function actionDelete($id)
    {
        if ($this->findModel($id)->delete()) {
            return $this->message("删除成功", $this->redirect(['index']));
        }

        return $this->message("删除失败", $this->redirect(['index']), 'error');
    }

    /**
     * 导出
     */
    public function actionExport()
    {

        $header = [
            ['巡更点', 'place.name'],
            ['巡更班次', 'patrolClasses.title'],
            ['巡更员工', 'member.realname'],
            ['巡更点状态', 'state', 'selectd', \addons\Patrol\common\enums\PlaceEnum::getMap()],
            ['备注', 'mark'],
            ['巡更时间', 'created_at', 'date', 'Y-m-d H:i:s'],
        ];
        $params= $SearchModel = Yii::$app->request->queryParams;
        unset($SearchModel['place_realname']);
        unset($SearchModel['patrolClasses_title']);
        unset($SearchModel['member_realname']);
        unset($SearchModel['created_at']);
//        unset($SearchModel['state']);
        foreach ($SearchModel as $name => $value) {
            if( !$value )
                unset($SearchModel[$name] );
        }
        Yii::$app->debris->p($SearchModel);

        $created_time = [];
        if(!empty($params['created_at'])){
            list($start,$end) = explode('/',$params['created_at']);
            $start = strtotime($start);
            $end = strtotime($end);
            $created_time = ['between',PatrolRecord::tableName().'.created_at',$start,$end];
        }
        Yii::$app->debris->p($created_time);

        $list = PatrolRecord::find()->select('*')
            ->andWhere(['status' => StatusEnum::ENABLED,'merchant_id'=>Yii::$app->user->identity->merchant_id])
            ->andFilterWhere($SearchModel)
            ->andFilterWhere($created_time)
            ->With(['member','patrolClasses','place'])
            ->orderBy(PatrolRecord::tableName().'.id DESC')
            ->asArray()
            ->all();
//        Yii::$app->debris->p($list);
        return ExcelHelper::exportData($list, $header);
    }
    protected function findModel($id)
    {
        /* @var $model \yii\db\ActiveRecord */
        if (empty($id) || empty(($model = $this->modelClass::findOne(['id' => $id, 'merchant_id' => $this->getMerchantId()])))) {

            $model = new $this->modelClass;
            return $model->loadDefaultValues();
        }

        return $model;
    }
}
